package com.meiyu.live.tv.widget;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.R;
import com.meiyu.live.popj.Gift;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by zbl on 2016/8/30.
 */
public class GiftShowView extends LinearLayout {

    private static final int ITEM_COUNT = 3;
    private static final long ANIMATION_DURATION = 500;
    private static final long GIFT_STAY_TIME = 2000;

    private LayoutInflater inflater;
    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private Handler handler = new Handler();
    private Gift[] giftPool = new Gift[ITEM_COUNT];
    private AnimationGiftMoveright[] animationGiftMoverights = new AnimationGiftMoveright[ITEM_COUNT];
    private Queue<Gift> giftQueue = new LinkedList<>();

    private View[] giftItemView = new View[ITEM_COUNT];
    private ImageView[] iv_avatar = new ImageView[ITEM_COUNT], iv_gift = new ImageView[ITEM_COUNT];
    private TextView[] tv_name = new TextView[ITEM_COUNT], tv_gifttext = new TextView[ITEM_COUNT], tv_giftcount = new TextView[ITEM_COUNT];

    private OnGiftShowListener listener;

    class AnimationGiftMoveright {
        private View anim_view, iv_gift;
        private AnimationSet animationSet;
        private Runnable startMoveupAnimation = new Runnable() {
            @Override
            public void run() {
                int index = (int) anim_view.getTag();
                animationGiftMoverights[index] = null;
                anim_view.startAnimation(new AnimationGiftMoveup(anim_view).getAnimationSet());
                if (listener != null) {
                    listener.onGiftShowFinish(giftPool[index]);
                }
            }
        };

        public AnimationSet getAnimationSet() {
            return animationSet;
        }

        public AnimationGiftMoveright(View view) {
            this.anim_view = view;
            this.iv_gift = view.findViewById(R.id.iv_gift);
            animationSet = new AnimationSet(true);
            animationSet.setDuration(ANIMATION_DURATION);

            TranslateAnimation animation_gift_moveright = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f);
            animation_gift_moveright.setDuration(ANIMATION_DURATION);
            animation_gift_moveright.setFillAfter(true);
            animation_gift_moveright.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    anim_view.setAlpha(1f);
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    handler.postDelayed(startMoveupAnimation, GIFT_STAY_TIME);
                    startScaleAnimation(iv_gift);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            AlphaAnimation animation_gift_fade_in = new AlphaAnimation(0f, 1f);
            animation_gift_fade_in.setDuration(ANIMATION_DURATION);
            animation_gift_fade_in.setFillAfter(true);
            animationSet.addAnimation(animation_gift_moveright);
            animationSet.addAnimation(animation_gift_fade_in);
        }

        public void resetStayTime() {
            int index = (int) anim_view.getTag();
            if (animationGiftMoverights[index] != null) {
                handler.removeCallbacks(startMoveupAnimation);
                handler.postDelayed(startMoveupAnimation, GIFT_STAY_TIME);
            }
        }
    }

    class AnimationGiftMoveup {
        private View anim_view;
        private AnimationSet animationSet;

        public AnimationSet getAnimationSet() {
            return animationSet;
        }

        public AnimationGiftMoveup(View view) {
            this.anim_view = view;
            animationSet = new AnimationSet(true);
            animationSet.setDuration(ANIMATION_DURATION);
            TranslateAnimation animation_gift_moveup = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                    Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, -1f);
            animation_gift_moveup.setDuration(ANIMATION_DURATION);
            animation_gift_moveup.setFillAfter(true);
            animation_gift_moveup.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    anim_view.setAlpha(1f);
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    int index = (int) anim_view.getTag();
                    giftPool[index] = null;
                    anim_view.setAlpha(0f);

                    Gift gift = giftQueue.poll();
                    if (gift != null) {
                        addGift(gift);
                    }
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            AlphaAnimation animation_gift_fade_out = new AlphaAnimation(1f, 0f);
            animation_gift_fade_out.setDuration(ANIMATION_DURATION);
            animation_gift_fade_out.setFillAfter(true);
            animationSet.addAnimation(animation_gift_moveup);
            animationSet.addAnimation(animation_gift_fade_out);
        }
    }

    private void startScaleAnimation(View view) {
        ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 1.5f, 1f, 1.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.5f, ScaleAnimation.RELATIVE_TO_SELF, 0.8f);
        scaleAnimation.setDuration(300);
        scaleAnimation.setRepeatCount(1);
        scaleAnimation.setRepeatMode(ScaleAnimation.REVERSE);
        scaleAnimation.setFillAfter(true);
        view.startAnimation(scaleAnimation);
    }

    private Runnable addGiftDelayTask = new Runnable() {
        @Override
        public void run() {
            Gift gift = giftQueue.poll();
            if (gift != null) {
                addGift(gift);
            }
        }
    };

    public GiftShowView(Context context) {
        super(context);
        init(context);
    }

    public GiftShowView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        inflater = LayoutInflater.from(context);
        setOrientation(LinearLayout.VERTICAL);
        for (int i = 0; i < ITEM_COUNT; i++) {
            giftItemView[i] = inflater.inflate(R.layout.view_gift_item, null);
            iv_avatar[i] = (ImageView) giftItemView[i].findViewById(R.id.iv_avatar);
            iv_gift[i] = (ImageView) giftItemView[i].findViewById(R.id.iv_gift);
            tv_name[i] = (TextView) giftItemView[i].findViewById(R.id.tv_name);
            tv_gifttext[i] = (TextView) giftItemView[i].findViewById(R.id.tv_gifttext);
            tv_giftcount[i] = (TextView) giftItemView[i].findViewById(R.id.tv_giftcount);
            giftItemView[i].setAlpha(0f);
            giftItemView[i].setTag(i);
            addView(giftItemView[i]);
        }
    }

    /**
     * 往队列中增加礼物
     *
     * @param gift
     * @return 0 gift对象为空，1 队列中有相同礼物数量累计，2 有空队列加入礼物，3 没有空队列礼物重新加入队列
     */
    public int addGift(Gift gift) {
        if (gift == null) {
            return 0;
        }

        //已有相同礼物，加数量
        for (int i = 0; i < ITEM_COUNT; i++) {
            final Gift giftInPool = giftPool[i];
            if (giftInPool != null && gift.gift_type != null && giftInPool.gift_type.equals(gift.gift_type) && giftInPool.net_ease_id.equals(gift.net_ease_id)) {
                if (animationGiftMoverights[i] != null) {
                    animationGiftMoverights[i].resetStayTime();
                }
                giftInPool.gift_count += gift.gift_count;
                tv_giftcount[i].setText("X " + giftInPool.gift_count);
                tv_giftcount[i].clearAnimation();
                tv_giftcount[i].startAnimation(AnimationUtils.loadAnimation(getContext(), R.anim.sweet_in));
                handler.postDelayed(addGiftDelayTask, ANIMATION_DURATION * 2);
                return 1;
            }
        }

        for (int i = 0; i < ITEM_COUNT; i++) {
            if (giftPool[i] == null) {
                giftPool[i] = gift;
                tv_name[i].setText(gift.name);
                tv_gifttext[i].setText("送了一个" + gift.gift_name);
                imageLoader.displayImage(gift.icon, iv_avatar[i], options);
                imageLoader.displayImage(gift.gift_icon, iv_gift[i], options);
                tv_giftcount[i].setText("X " + gift.gift_count);
                giftItemView[i].clearAnimation();
                animationGiftMoverights[i] = new AnimationGiftMoveright(giftItemView[i]);
                giftItemView[i].startAnimation(animationGiftMoverights[i].getAnimationSet());
                handler.postDelayed(addGiftDelayTask, ANIMATION_DURATION * 2);
                return 2;
            }
        }
        giftQueue.offer(gift);
        return 3;
    }

    public void setOnGiftShowListener(OnGiftShowListener listener) {
        this.listener = listener;
    }

    public interface OnGiftShowListener {
        void onGiftShowFinish(Gift gift);
    }
}
